#include "stm32f4xx_it.h"
#include "main.h"
#include "Int_led.h"
#include "Int_EEPROM.h"
#include "Dri_Uart.h"
#include "Com_Debug.h"

/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
static __IO uint32_t uwTimingDelay;
RCC_ClocksTypeDef RCC_Clocks;

/* Private function prototypes -----------------------------------------------*/

/* Private functions ---------------------------------------------------------*/

/**
 * @brief  Main program
 * @param  None
 * @retval None
 */
int main(void)
{
  /* 获取系统时钟频率 */
  RCC_GetClocksFreq(&RCC_Clocks);

  /* 配置SysTick定时器，产生1ms中断 */
  SysTick_Config(RCC_Clocks.HCLK_Frequency / 1000);

  /* 初始化LED */
  Int_LED_Init();
  /* 初始化UART */
  Dri_Uart_Init();
  /* 配置EEPROM */
  Int_EEPROM_Init();

  /* 添加延时确保EEPROM初始化完成 */
  Delay(100); // 延时100ms，确保I2C稳定

  /* UART测试 - 发送启动信息 */
  Dri_Uart_SendString("STM32F407 UART Test Started!\r\n");
  Dri_Uart_SendString("Starting EEPROM Test...\r\n");

  // 首先检查EEPROM设备是否存在
  if (Int_EEPROM_IsDeviceReady(EEPROM_DEV1_ADDR))
  {
    Dri_Uart_SendString("EEPROM Device Found at 0x50!\r\n");

    // 测试写入
    if (Int_EEPROM_Write(EEPROM_DEV1_ADDR, 0x0000, 0x55))
    {
      Dri_Uart_SendString("EEPROM Write Success!\r\n");

      // 等待写入完成
      Delay(20);

      // 测试读取
      uint8_t data = 0;
      if (Int_EEPROM_Read(EEPROM_DEV1_ADDR, 0x0000, &data))
      {
        if (data == 0x55)
        {
          Dri_Uart_SendString("EEPROM Test Passed! Data=0x55\r\n");
        }
      }
      else
      {
        Dri_Uart_SendString("EEPROM Read Failed!\r\n");
      }
    }
    else
    {
      Dri_Uart_SendString("EEPROM Write Failed!\r\n");
    }
  }
  while (1)
  {

  }
}

/**
 * @brief  Inserts a delay time.
 * @param  nTime: specifies the delay time length, in milliseconds.
 * @retval None
 */
void Delay(__IO uint32_t nTime)
{
  uwTimingDelay = nTime;

  while (uwTimingDelay != 0)
    ;
}

/**
 * @brief  Decrements the TimingDelay variable.
 * @param  None
 * @retval None
 */
void TimingDelay_Decrement(void)
{
  if (uwTimingDelay != 0x00)
  {
    uwTimingDelay--;
  }
}

#ifdef USE_FULL_ASSERT

/**
 * @brief  Reports the name of the source file and the source line number
 *         where the assert_param error has occurred.
 * @param  file: pointer to the source file name
 * @param  line: assert_param error line source number
 * @retval None
 */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */

  /* Infinite loop */
  while (1)
  {
  }
}
#endif
